﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Bzure.Common.Core;
using Bzure.Security.Principal;

namespace Bzure.Security.Permissions
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    [Serializable]
    public class AuthorizeBaseAttribute : AuthorizeAttribute
    {
        [Obsolete("属性被禁用，请使用CustomerRoles属性", true)]
        public new string Roles
        {
            get;

            set;
        }
        [Obsolete("属性被禁用，请使用CustomerRoles属性", true)]
        public new string Users
        {
            get;

            set;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            base.OnAuthorization(filterContext);

            if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult(

                   string.Concat(FormsAuthentication.LoginUrl,

                                "?code=1", "&ReturnUrl=",
                                     filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri)));

            }



        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            foreach (IAccessCode code in codes)
                this._droit.AddAccessCode(code);
            IDroit droit = this._droit.Copy();

            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            BzurePrincipal principal = httpContext.User as BzurePrincipal;
            if (principal == default(BzurePrincipal))
                return false;
            return principal.GetPermission().Authentication(droit);
        }


        private IDroit _droit;
        public IDroit Droit
        {
            get { return _droit; }
        }
        public string ResourceID
        {
            get { throw new NotSupportedException("this method is not ResourceID"); }
            set
            {
                if (value != null)
                {
                    _droit = new Droit(value);
                }
            }
        }
        List<IAccessCode> codes = new List<IAccessCode>();
        protected void AddAccessCode(IAccessCode accessCode)
        {
            codes.Add(accessCode);
        }
        protected void AddAccessCodeValue(int codeValue)
        {
            this.AddAccessCode(new AccessCode(codeValue));
        }
        protected void SetAccessCodes<T>(T requiredRight) where T : struct
        {
            foreach (T right in requiredRight.Parse())
            {
                this.AddAccessCodeValue(Convert.ToInt32(right));
            }
        }
    }
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    [Serializable]
    public class BzureAuthorizeAttribute : AuthorizeBaseAttribute
    {
        public string RequiredRights
        {
            get { throw new NotSupportedException("this method is not supported"); }
            set
            {
                if (value != null)
                {
                    string[] ss = value.Split(',');
                    for (int i = 0; i < ss.Length; i++)
                        this.AddAccessCodeValue(Convert.ToInt32(ss[i]));
                }
            }
        }
    }


    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    [Serializable]
    public abstract class SimpleAuthorizeBaseAttribute : AuthorizeBaseAttribute
    {
        protected void SetRight<T>(T requiredRight) where T : struct
        {
            this.ResourceID = typeof(T).FullName;
            this.SetAccessCodes<T>(requiredRight);
        }
    }
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    [Serializable]
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        [Obsolete("属性被禁用，请使用CustomerRoles属性", true)]
        public new string Roles
        {
            get;
            set;
        }
        public new string Users
        {
            get;
            set;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            BzurePrincipal principal = httpContext.User as BzurePrincipal;
            if (principal == default(BzurePrincipal))
                return false;
            if (Users.Split(',').Contains(principal.Identity.Name))
                return true;
            return false;
        }

    }
}
